<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模块编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入模块编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模块名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模块名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模块型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入模块型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="驱动编码" prop="driveCode">
        <el-input
          v-model="queryParams.driveCode"
          placeholder="请输入驱动编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:module:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:module:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:module:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['device:module:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['device:module:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="moduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模块编码" align="center" prop="code" width="190"/>
      <el-table-column label="模块名称" align="center" prop="name"/>
      <el-table-column label="模块型号" align="center" prop="model"/>
       <el-table-column label="驱动名称" align="center" prop="driveName">
       <template slot-scope="scope">
         <el-tooltip effect="light"  placement="top-start">
           <template slot="content">插件库名称：{{scope.row.adapterName}}</template>
           <span>{{ scope.row.driveName }}</span>
         </el-tooltip>
       </template>
     </el-table-column>
      <el-table-column label="规格" align="center" prop="spec"/>
      <!-- <el-table-column label="品牌编码" align="center" prop="brandCode" /> -->
      <el-table-column label="品牌名称" align="center" prop="brandName"/>

      <el-table-column label="描述" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:module:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:module:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模块对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="closeE" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模块编码" prop="code" v-if="form.id">
          <el-input v-model="form.code" disabled />
        </el-form-item>
        <el-form-item label="模块名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模块名称"/>
        </el-form-item>
        <el-form-item label="模块型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入模块型号"/>
        </el-form-item>
        <el-form-item label="设备驱动" prop="driveCode">
          <el-select
            v-model="form.driveCode"
            placeholder="请选择设备驱动"
            filterable
            clearable
            @change="handleDriveChange"
          >
            <el-option
              v-for="item in driveOptions"
              :key="item.id"
              :label="item.driveName"
              :value="item.driveCode"
            >
              <el-tooltip effect="light"  placement="top-start">
                <template slot="content">插件库名称：{{item.adapterName}}</template>
                <span>{{ item.driveName }}</span>
              </el-tooltip>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="form.spec" placeholder="请输入规格"/>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-select
            v-model="form.brand"
            value-key="code"
            placeholder="品牌"
            clearable
            filterable
            @change="changeSelect($event)"
          >

            <div v-for="bra in deBrands" :key="bra.code">
              <el-tooltip effect="dark" content="已停用" placement="top-start">
                <el-option
                  disabled
                  :key="bra.code"
                  :label="bra.name"
                  :value="bra"
                />
              </el-tooltip>
            </div>
            <el-option
              v-for="mau in brands"
              :key="mau.code"
              :label="mau.name"
              :value="mau"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  删除模块失败提示-->
    <el-dialog
      :visible.sync="deleteFailedDialogVisible"
      top="100px !important"
      width="800px"
      :close-on-click-modal="false"
      z-index="1002"
    >
      <template slot="title">
        提示：<span class="tip" style="color: red">模块被以下设备引用，若要删除，请先从设备管理界面解绑该设备对应的模块！</span>
      </template>
      <el-table :data="moduleInUsedList" max-height="600px">
        <el-table-column property="code" label="设备编码" width="190" align="center"/>
        <el-table-column property="name" label="设备名称" align="center"/>
        <el-table-column property="deleteModelCode" label="引用模块编码" width="190" align="center"/>
        <el-table-column property="deleteModelName" label="引用模块名称" align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="navToDeviceInfoUnbind(scope.row)">去解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteFailedDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>

    <import-file-dialog
      v-model="uploadDialogVisible"
      templateFileName="模块信息导入模板"
      uploadApi="/device/module/import"
      templateDownloadUrl="/device/module/export"
      @onSuccess="handleUploadFileSuccess"
    />
  </div>
</template>

<style scoped>

</style>

<script>
import {listModule, getModule, delModule, addModule, updateModule} from "@/api/device/module";

export default {
  name: "DeviceModule",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模块表格数据
      moduleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //停用的品牌
      deBrands: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        model: null,
        brandName: null,
        brand: null,
        status: 0,
        remark: null,
        driveCode: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "模块名称不能为空", trigger: "blur"}
        ],
        model: [
          {required: true, message: "模块型号不能为空", trigger: "blur"}
        ],
        spec: [
          {required: true, message: "设备规格不能为空", trigger: "blur"}
        ],
        brand: [
          {required: true, message: "品牌不能为空", trigger: "change"}
        ],
        driveCode: [
          {required: true, message: "设备驱动不能为空", trigger: "change"}
        ],
      },
      // 设备被引用中弹窗
      deleteFailedDialogVisible: false,
      // 模块被设备引用列表
      moduleInUsedList: [],
      // 导入文件弹窗
      uploadDialogVisible: false,
    };
  },
  created() {
    this.$store.dispatch('LoadDriveOption');
    // this.getList();
  },

  computed: {
    //有效的品牌，用于下拉列表
    brands() {
      return this.$store.state.device.brands || []
    },
    // 驱动选项
    driveOptions() {
      return this.$store.state.device.driveOptions || []
    },
  },

  methods: {
    // 导入文件上传成功
    handleUploadFileSuccess(res) {
      if (res.data === "上传成功！") this.getList()
    },
    handleImport() {
      this.uploadDialogVisible = true
    },
    // 跳转到设备管理页面解绑
    navToDeviceInfoUnbind(row){
      this.deleteFailedDialogVisible = false;
      this.$router.push({
        path: '/device/deviceInfo',
        query: {moduleCode: row.deleteModelCode}
      })
    },

    handleDriveChange(value){
      const driveData = this.driveOptions.find(item =>{
        return item.driveCode === value
      })
      this.form.driveName = driveData.driveName;
      this.form.adapterName = driveData.adapterName;
    },
    /**品牌下拉列表更改 */
    changeSelect(selection) {
      this.form.brandCode = selection.code;
      this.form.brandName = selection.name;
    },

    //对话框关闭是的回调函数
    closeE() {
      this.reset();
      this.deBrands = [];
    },

    /** 查询模块列表 */
    getList() {
      this.loading = true;
      listModule(this.queryParams).then(response => {
        // 是否已经加载过设备列表标记改为true
        if (!this.alreadyGetList) this.alreadyGetList = true;
        this.moduleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        model: null,
        brandCode: null,
        brandName: null,
        subNumber: null,
        spec: null,
        brand: null,
        driveCode: null,
        driveName: null,
        adapterName: null,
        status: 0,//新增窗口打开时状态默认正常
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.driveCode = null;
      this.queryParams.brandName = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模块";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getModule(id).then(response => {
        this.brands.forEach(element => {
          if (element.code === row.brandCode) {
            response.data.brand = element;
          }
        })

        //如果当前选中的模块所属的品牌已经停用，则显示模块表的品牌code和品牌名称
        if (response.data.brand === undefined) {
          response.data.brand = {code: response.data.brandCode, name: response.data.brandName};
          this.deBrands.push({code: response.data.brandCode, name: response.data.brandName});
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改模块";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateModule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              // 更新vuex的设备模块
              this.$store.dispatch('LoadDeviceModules');
            });
          } else {
            addModule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 更新vuex的设备模块
              this.$store.dispatch('LoadDeviceModules');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选模块？').then(() => {
        this.loading = true;
        return delModule(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        // 更新vuex的设备模块
        this.$store.dispatch('LoadDeviceModules');
      }).catch((res) => {
        this.loading = false;
        const list = res.data;
        if (list.length) {
          this.moduleInUsedList = list;
          this.deleteFailedDialogVisible = true;
        }
        // console.log(list,'删除失败')
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      this.download('device/module/export', {
        ...this.queryParams,
        exportBlank: '0'
      }, `模块管理_${currentDate}.xlsx`)
    }
  },
  beforeRouteEnter(to,from,next){
    const {driveCode,brandName} = to.query;
    // 如果存在跳转参数driveCode,自动填入查询条件
    if(driveCode || brandName){
      next(vm => {
        vm.resetForm("queryForm");
        vm.queryParams.driveCode = driveCode;
        vm.queryParams.brandName = brandName;
        vm.getList();
      })
    } else {
      // 不存在查询参数
      next(vm => {
        // 判断是否已经加载过列表了，当还没有加载过列表时才调用获取列表接口
        if (!vm.alreadyGetList){
          vm.getList();
        }
      });
    }
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
</style>
